<template>
  <slide-view
    v-empty="!canShowDetail"
    :listener-ids="listenerIDs"
    :no-listener-ids="noListenerIDs"
    :no-listener-class="noListenerClass"
    :body-style="{padding: 0, height: '100%'}"
    xs-empty-icon="nopermission"
    :xs-empty-text="$t('crm.invoice.bb62910bec9a3638df2e215d42986ff4')"
    @afterEnter="viewAfterEnter"
    @close="hideView">
    <div ref="crmDetailMain" v-loading="loading" class="detail-main no-padding">
      <flexbox
        v-if="canShowDetail && detailData"
        direction="column"
        align="stretch"
        class="d-container">
        <wk-detail-header
          :subtitle="$t('crm.invoice.dff41322e8c992ec1c28b344b4ed0229')"
          :class="{'is-shadow': bodyIsScroll}"
          :title="detailData.invoiceApplyNumber"
          :page-list="pageList"
          :dropdowns="handleOperations"
          @command="headerRightClick"
          @pageChange="pageChange"
        >
          <template slot="left">
            <span v-if="detailData.checkStatus == 13" class="is-invalid">（已终止）</span>
            <span v-if="detailData.checkStatus == 14" class="is-invalid">（已归档）</span>
            <el-tooltip :content="detailData.star == 0 ? '添加关注' : '取消关注'" effect="dark" placement="top">
              <i
                v-if="detailData.star == 0"
                class="el-icon-star-off focus-icon"
                @click="toggleStar()" />
              <i
                v-else
                class="wk wk-focus-on focus-icon active"
                @click="toggleStar()" />
            </el-tooltip>
          </template>

          <template slot="right">
            <time-piece v-if="showTimer && isCall" />
            <el-button
              v-if="showTransfer"
              class="head-handle-button"
              @click="headerRightClick('transfer')">
              {{ $t('crm.invoice.8cea4918fe8fd5e981db0d2f36d7a746') }}
            </el-button>
            <el-button
              v-if="showEdit"
              class="head-handle-button"
              type="primary"
              @click="headerRightClick('edit')">
              {{ $t('crm.invoice.c3fa1924675d94d74de8ddaf4cd050bd') }}
            </el-button>
          </template>
        </wk-detail-header>

        <!-- 标签 -->
        <flexbox v-if="tagInfo" wrap="wrap" class="wk-tags-content">
          <tag-view :value="tagInfo.value" :max-length="Infinity" wrap="wrap">
            <wk-tag
              v-model="tagInfo.value"
              :disabled="tagInfo.disabled"
              :placeholder="tagInfo.placeholder"
              :data="tagInfo"
              :options="tagInfo.setting"
              @change="tagChange($event)">
              <el-tooltip
                slot="reference"
                :content="$t('crm.invoice.b012733d1112aef34e88fc1ec34e93f4')"
                effect="dark"
                placement="top">
                <el-button
                  type="icon"
                  size="small"
                  icon="wk wk-icon-label-solid" />
              </el-tooltip>
            </wk-tag>
          </tag-view>
        </flexbox>

        <div class="d-container-body" @scroll="bodyScroll">
          <detail-head-base :list="headDetails" />
          <relative-stage-records
            :id="id"
            :crm-type="crmType"
            :is-stage-flow="true"
            :detail="detailData"
            @handle="detailHeadHandle" />
          <flexbox
            class="left-right-wrap"
            :class="{'is-hidden-right': !detailData.examineRecordId }"
            align="stretch">
            <div class="left">
              <el-tabs v-model="tabCurrentName" nav-mode="more">
                <el-tab-pane
                  v-for="(item, index) in tabNames"
                  :key="index"
                  :label="item.label"
                  :name="item.name"
                  lazy>
                  <template slot="label">
                    <el-badge
                      :value="item.num"
                      :hidden="item.num <= 0"
                      type="primary">
                      {{ item.label }}
                    </el-badge>
                  </template>
                  <component
                    :is="item.name"
                    :id="id"
                    :ref="item.name"
                    :detail="detailData"
                    :crm-type="crmType"
                    :other-list="baseDetailList"
                    :ignore-fields="['invoiceType']"
                    @handle="detailHeadHandle" />
                </el-tab-pane>
              </el-tabs>
            </div>
            <div class="right">
              <examine-info-section
                v-if="detailData.examineRecordId"
                :id="id"
                :record-id="detailData.examineRecordId"
                examine-type="crm_invoice"
                @on-handle="examineHandle" />
            </div>
          </flexbox>
        </div>
      </flexbox>
    </div>

    <!-- 新建编辑 -->
    <create
      v-if="crmCreateShow"
      :action="createActionInfo"
      :examine-info="examineInfo"
      @save-success="editSaveSuccess"
      @close="crmCreateShow = false" />

    <!-- 转移 -->
    <transfer-handle
      v-if="transferDialogShow"
      :props="transferHandleProps"
      :dialog-visible.sync="transferDialogShow"
      @handle="detailHeadHandle({type: 'transfer'})" />
  </slide-view>
</template>

<script>
import {
  crmInvoiceReadAPI,
  crmInvoiceDeleteIdsAPI
} from '@/api/crm/invoice'

import SlideView from '@/components/SlideView'
import TransferHandle from '@/components/Page/SelectionHandle/TransferHandle' // 转移
import RelativeStageRecords from '../components/RelativeStageRecords' // 阶段记录
import CRMEditBaseInfo from '../components/CRMEditBaseInfo' // 基本信息
import RelativeFiles from '../components/RelativeFiles' // 相关附件
import RelativeHandle from '../components/RelativeHandle' // 相关操作
import ExamineInfoSection from '@/components/Examine/ExamineInfoSection'
import Create from './Create'

import DetailMixin from '../mixins/Detail'
import { separator } from '@/filters/vueNumeralFilter/filters'

export default {
  // 学员管理 的 发票详情
  name: 'InvoiceDetail',
  components: {
    SlideView,
    TransferHandle,
    RelativeStageRecords,
    CRMEditBaseInfo,
    RelativeFiles,
    RelativeHandle,
    ExamineInfoSection,
    Create
  },
  mixins: [DetailMixin],
  props: {
    // 详情信息id
    id: [String, Number],
    // 监听的dom 进行隐藏详情
    listenerIDs: {
      type: Array,
      default: () => {
        return ['crm-main-container']
      }
    },
    // 不监听
    noListenerIDs: {
      type: Array,
      default: () => {
        return []
      }
    },
    noListenerClass: {
      type: Array,
      default: () => {
        return ['el-table__body']
      }
    }
  },
  data() {
    return {
      // 展示加载loading
      loading: false,
      crmType: 'invoice',
      // 名称
      name: '',
      headDetails: [],
      tabCurrentName: 'CRMEditBaseInfo',
      baseDetailList: [] // 基本详情list
    }
  },
  computed: {
    // 可操作选项
    handleOperations() {
      return this.getOperations(['delete'])
    },

    // tabs
    tabNames() {
      var tempsTabs = [
        { label: this.$t('crm.invoice.6f465bcd13a48c2f8efb9fb5442c8db3'), name: 'CRMEditBaseInfo' },
        {
          label: this.$t('crm.invoice.d2c3db78ea47a1c315a48269a8c7d226'), num: this.tabsNumber.fileCount,
          name: 'RelativeFiles'
        }
      ]
      if (this.userInfo.loginType != 3) {
        tempsTabs.push({ label: this.$t('crm.invoice.3a358db1c68f8df390d9033c8a0be09a'), name: 'RelativeHandle' })
      }
      return tempsTabs
    }
  },
  mounted() {},
  methods: {
    /**
     * 详情
     */
    getDetial() {
      this.loading = true
      crmInvoiceReadAPI(this.id)
        .then(res => {
          this.loading = false
          const resData = res.data || {}
          this.name = resData.invoiceNumber
          this.detailData = resData
          this.getBaseList(resData)

          // 负责人
          this.headDetails = [
            { title: '客户名称', value: resData.customerName },
            { title: `开票金额（${this.crmMoneyUnit}）`, value: separator(this.crmMoney(resData.invoiceMoney || 0)) },
            { title: '发票号码', value: resData.invoiceNumber },
            { title: '实际开票日期', value: resData.realInvoiceDate }
          ]
        })
        .catch(() => {
          this.loading = false
          this.hideView()
        })
    },

    /**
     * 获取基本信息数据
     */
    getBaseList(data) {
      this.baseDetailList = [
        // {
        //   name: '基本信息',
        //   list: [
        //     {
        //       name: '发票申请编号',
        //       formType: 'text',
        //       value: data.invoiceApplyNumber
        //     },
        //     {
        //       name: '客户名称',
        //       formType: 'customer',
        //       value: data
        //     },
        //     {
        //       name: '合同编号',
        //       formType: 'contract',
        //       value: data
        //     },
        //     {
        //       name: '合同金额',
        //       formType: 'text',
        //       value: data.contractMoney
        //     },
        //     {
        //       name: '开票金额（元）',
        //       formType: 'text',
        //       value: data.invoiceMoney
        //     },
        //     {
        //       name: '开票日期',
        //       formType: 'text',
        //       value: data.invoiceDate
        //     },
        //     {
        //       name: '开票类型',
        //       formType: 'text',
        //       value: {
        //         1: '增值税专用发票',
        //         2: '增值税普通发票',
        //         3: '国税通用机打发票',
        //         4: '地税通用机打发票',
        //         5: '收据'
        //       }[data.invoiceType]
        //     },
        //     {
        //       name: '备注',
        //       formType: 'text',
        //       value: data.remark
        //     },
        //     {
        //       name: '创建人',
        //       formType: 'text',
        //       value: data.createUserName
        //     },
        //     {
        //       name: '负责人',
        //       formType: 'text',
        //       value: data.ownerUserName
        //     },
        //     {
        //       name: '创建时间',
        //       formType: 'text',
        //       value: data.createTime
        //     },
        //     {
        //       name: '更新时间',
        //       formType: 'text',
        //       value: data.updateTime
        //     }
        //   ]
        // },
        {
          name: this.$t('crm.invoice.9051fb31736f5bd01c38214900b22179'),
          list: [
            {
              name: this.$t('crm.invoice.ad13ccc1eec3d37a191d4d4d9e83012c'),
              formType: 'text',
              value: {
                1: this.$t('crm.invoice.34981a4351dec722c2bfe8c1ba6a8a38'),
                2: this.$t('crm.invoice.745c84b3f74a49e2346178493c6b846a')
              }[data.titleType]
            },
            {
              name: this.$t('crm.invoice.7eed12e3f833b3e4752809de6259ea82'),
              formType: 'text',
              value: data.invoiceTitle
            },
            {
              name: this.$t('crm.invoice.35cf7da77e109153b4e02412467b1f93'),
              formType: 'text',
              value: data.taxNumber
            },
            {
              name: this.$t('crm.invoice.ea6ab9959730d850bf6192f813a44c1b'),
              formType: 'text',
              value: data.depositBank
            },
            {
              name: this.$t('crm.invoice.b421ee1fe4e913aa066de8070693cb98'),
              formType: 'text',
              value: data.depositAccount
            },
            {
              name: this.$t('crm.invoice.cae5b737c211ed91e3116bfe0aca7837'),
              formType: 'text',
              value: data.depositAddress
            },
            {
              name: this.$t('crm.invoice.f60b77f67deebb4e1ec6adcc193a1dfa'),
              formType: 'text',
              value: data.telephone
            }
          ]
        },
        {
          name: this.$t('crm.invoice.95dfe02521b5a004f004b0cc4171efcb'),
          list: [
            {
              name: this.$t('crm.invoice.8357331fe5978014aebae01a38473af9'),
              formType: 'text',
              value: data.contactsName
            },
            {
              name: this.$t('crm.invoice.61f2a205a0052ecf41f914c5936800cf'),
              formType: 'text',
              value: data.contactsMobile
            },
            {
              name: this.$t('crm.invoice.40c6879ecfbfc59be6bc32fadf891a79'),
              formType: 'position',
              value: data.contactsAddress || []
            }
          ]
        }
      ]
    },

    /**
     * 关闭
     */
    hideView() {
      this.$emit('hide-view')
    },

    /**
     * 审核操作
     */
    examineHandle() {
      this.detailHeadHandle({ type: 'examine' })
    },

    /* ------------------------ 头部事件 ------------------------ */
    /**
     * @description: 头部右侧点击事件
     * @param {*}
     * @return {*}
     */
    headerRightClick(type) {
      if (type === 'transfer') {
        this.transferDialogShow = true
      } else if (type === 'edit') {
        if (this.detailData.checkStatus === 1) {
          this.$message.error('已通过的发票不可以编辑')
          return false
        } else if (this.detailData.checkStatus === 3) {
          this.$message.error('审核中的发票撤回后才可编辑')
          return false
        } else {
          this.createCRMType = this.crmType
          this.createActionInfo = {
            type: 'update',
            id: this.id,
            batchId: this.detailData.batchId,
            detail: this.detailData
          }

          this.examineInfo = {
            examineStatus: this.detailData.checkStatus,
            recordId: this.detailData.examineRecordId
          }

          this.crmCreateShow = true
        }
      } else if (type == 'delete') {
        this.$confirm(
          this.$t('crm.invoice.6c6e786c1795a5953917b01a534d3f7f'),
          this.$t('crm.invoice.42e749a34ec600e71512072dcf139112'),
          {
            confirmButtonText: this.$t('crm.invoice.8fd4ee743ede13780885802f08f7c6f4'),
            cancelButtonText: this.$t('crm.invoice.5523f1049e3e718f961113ad2fd743b2'),
            type: 'warning'
          }
        )
          .then(() => {
            crmInvoiceDeleteIdsAPI([this.id])
              .then(res => {
                this.$message({
                  type: 'success',
                  message: this.$t('crm.invoice.a04707f1c5b8bed372b1c246932d5a2b')
                })
                this.detailHeadHandle({ type })
              })
              .catch(() => {})
          })
          .catch(() => {})
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../styles/crmdetail.scss";

.d-container-body {
  margin-top: 8px;
}
</style>
